
using UnityEditor;
using UnityEngine;

namespace HotUpdate.Editor {
    public abstract class AssetNameAttributeDrawer<T> : PropertyDrawer where T:Object
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var nameRect = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight);
            DrawAssetName(nameRect, property);
            var assetRect = new Rect(position.x, position.y + EditorGUIUtility.singleLineHeight, position.width, position.height - EditorGUIUtility.singleLineHeight);
            DrawAsset(assetRect,property);
        }
        
        private void DrawAssetName(Rect position, SerializedProperty property)
        {
            EditorGUI.LabelField(position, property.displayName, property.stringValue);
        }
        private void DrawAsset(Rect position, SerializedProperty property)
        {
            EditorGUI.BeginChangeCheck();
            var asset = EditorGUI.ObjectField(position, property.displayName, AssetDatabase.LoadAssetAtPath(property.stringValue, typeof(T)) as T, typeof(T), false);
            if (EditorGUI.EndChangeCheck())
            {
                if (asset != null)
                {
                    property.stringValue = AssetDatabase.GetAssetPath(asset);
                }
                else
                {
                    property.stringValue = "";
                }
            }
        }
        protected virtual float GetAssetHeight(SerializedProperty property, GUIContent label)
        {
            return EditorGUI.GetPropertyHeight(SerializedPropertyType.ObjectReference, label);
        }
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            return GetAssetHeight(property,label) + EditorGUIUtility.singleLineHeight;
        }
    }

}

